#include<iostream>
#include<unistd.h>
#include<cassert>
#include<cstdio>
#include<sys/types.h>
#include<sys/wait.h>
#include<string>
#include<cstring>

//父进程进行读取，子进程进行写入
int main()
{
    
    // std::cout<<"hello c++"<<std::endl;
    //1.创建管道文件，打开读写端
    int fds[2];
    int n = pipe(fds);
    assert(n == 0);
    //2.fork
    pid_t id = fork();
    assert(id >= 0);
    if(id == 0)
    {
        close(fds[0]);
        const char* s = "我是子进程，我正在给你发消息";
        int cnt = 0;
        while(true)
        {
            cnt++;
            char buffer[1024];//只有子进程能看到
            snprintf(buffer,sizeof buffer,"child->parent say: %s[%d][%d]",s,cnt,getpid());
            //写端写满的时候，在写会阻塞，等对方进行读取
            write(fds[1],buffer,strlen(buffer));
            //sleep(1);//每隔1s写一次
            //sleep(50);
            std::cout<<"count: "<<cnt<<std::endl;
            //break;
        }
        close(fds[1]);
        //sleep(10000);
        exit(0);
    }
    close(fds[1]);
    while(true)
    {
        sleep(2);
        //sleep(1000);
        char buffer[1024];
        std::cout<<"AAAAAAAAAAAAAAAAA"<<std::endl;
        //如果管道中没有了数据，读端在读，默认会直接阻塞当前正在读取的进程！
        ssize_t s = read(fds[0],buffer,sizeof(buffer) - 1);//读取的时候，按sizeof(buffer) - 1读取
        std::cout<<"BBBBBBBBBBBBBBBBB"<<std::endl;
        if(s > 0) {buffer[s] = 0;
        std::cout<<"Get Message# "<<buffer<<" | my pid: "<<getpid()<<std::endl;}
        else if(s == 0)
        {
            //读到文件结尾
            std::cout<<"read : "<<s<<std::endl;
            break;
        }
        //父进程没有进行sleep;
        break;
    }
    close(fds[0]);
    int status = 0;
    n = waitpid(id,&status,0);
    assert(n == id);
    std::cout<<"pid-> "<<n<<" : "<<(status & 0x7F)<<std::endl;
    // std::cout<<"fds[0]: "<<fds[0]<<std::endl;
    // std::cout<<"fds[1]: "<<fds[1]<<std::endl;
    return 0;
}